<template>
    <el-config-provider :locale="zhCn">
        <header-view :proj-name="projName" @menu-select="menuSelect">
            <template #main-content>
                <router-view></router-view>
            </template>
        </header-view>
    </el-config-provider>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import zhCn from  'element-plus/es/locale/lang/zh-cn'
import HeaderView from './complex-view/header-view/header-view.vue'
import $curl from '$aegisCommon/curl.js'
import { useProjectStore } from '$aegisStore/project'
import { useMenuStore } from '$aegisStore/menu'

const router = useRouter()
const route = useRoute()
const projectStore = useProjectStore()
const menuStore = useMenuStore()


onMounted(() => { 
    getProjectList()
    getProjectConfig()
})
const projName = ref('')

// 添加路由就绪检查的辅助函数
function getRouteQuery() {
    if (!route || !route.query) {
        return {};
    }
    return route.query;
}

async function getProjectList() {
    // 安全地获取路由参数
    const query = getRouteQuery();
    const projKey = query.proj_key || '';
    
    const res = await $curl({
        method: 'get',
        url: '/api/project/list',
        query: {
            proj_key: projKey
        }
    })

    if (!res || !res.data || !res.success) {
        return;
    }

    projectStore.setProjectList(res.data)
}

async function getProjectConfig() {
    // 安全地获取路由参数
    const query = getRouteQuery();
    const projKey = query.proj_key || '';
    
    const res = await $curl({
        method: 'get',
        url: '/api/project',
        query: {
            proj_key: projKey
        }
    })

    if (!res || !res.data || !res.success) {
        return;
    }

    const { name, menu } = res.data

    projName.value = name

    menuStore.setMenuList(menu)
}

const menuSelect = function(menuItem) {
    // 安全地获取路由参数
    const query = getRouteQuery();
    const projKey = query.proj_key || '';
    
    const { moduleType, key, customConfig } = menuItem

    if (key === query.key) {return}

    const pathMap = {
        schema: '/schema',
        iframe: '/iframe',
        sider: '/sider',
        custom: customConfig?.path
    }

    router.push({
        path: `/view/dashboard${pathMap[moduleType]}`,
        query: {
            proj_key: projKey,
            key: key
        }
    })
 }



</script>

<style lang="less" scoped>
:deep(.el-main) {
    padding: 0;
}
</style>